package com.yskj.tms.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mysql.jdbc.V1toV2StatementInterceptorAdapter;
import com.yskj.tms.common.UsersById;
import com.yskj.tms.entity.*;
import com.yskj.tms.mapper.ReChargeMapper;
import com.yskj.tms.service.ReChargeService;
import com.yskj.tms.service.ShipInfoDetailService;
import com.yskj.tms.util.Decv;
import com.yskj.tms.util.FiledUtil;
import com.yskj.tms.util.StringUtil;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.util.*;

/**
 * Created by Administrator on 2018/5/11.
 */
@Controller
public class ShipInfoDetailController {
    @Autowired
    private ShipInfoDetailService shipInfoDetailService;

    @Autowired
    private ReChargeService reChargeService;

    private UsersById users = new UsersById();

    //详情管理
    @RequestMapping("/shipInfoDeail.do")
    public ModelAndView shipInfoDeailByQuery(@RequestParam("shipid") int shipid,HttpServletRequest request) throws Exception {
        ShipInfo shipInfo = shipInfoDetailService.selectShipInfoDetail(shipid);
        ReChargeDetail reChargeDetail =reChargeService.selectReChargeDetailByUserid(users.getUserid(request));
        ModelAndView mav =  new ModelAndView("/ship/shipDetail");
        mav.addObject("shipInfo",shipInfo);
        if(reChargeDetail !=null){
            mav.addObject("resecond",reChargeDetail.getResecond());
        }else {
            mav.addObject("resecond",0);
        }

        return mav;
    }

    //船舶详情
    @RequestMapping("/shiptextinfo.do")
    public ModelAndView shipTextinfoByQuery(@RequestParam("shipid") int shipid,HttpServletRequest request) throws Exception {
        ShipInfo shipInfo = shipInfoDetailService.selectShipInfoDetail(shipid);
        ModelAndView mav =  new ModelAndView("/ship/shipTextinfo");
        mav.addObject("shipInfo",shipInfo);
        return mav;
    }

    //航行轨迹
    @RequestMapping("/shipmap.do")
    public ModelAndView shipMapByQuery(@RequestParam("shipid") int shipid,HttpServletRequest request) throws Exception {
        ShipInfo shipInfo = shipInfoDetailService.selectShipInfoDetail(shipid);
        ModelAndView mav =  new ModelAndView("/ship/shipMap");
        mav.addObject("shipInfo",shipInfo);
        return mav;
    }

    //视频管理
    @RequestMapping("/shipvideo.do")
    public ModelAndView shipVideoByQuery(@RequestParam("shipid") int shipid,HttpServletRequest request) throws Exception {
        ShipInfo shipInfo = shipInfoDetailService.selectShipInfoDetail(shipid);
        ReChargeDetail reChargeDetail =reChargeService.selectReChargeDetailByUserid(users.getUserid(request));
        ModelAndView mav =  new ModelAndView("/ship/shipVideo");
        mav.addObject("shipInfo",shipInfo);
        if(reChargeDetail !=null){
            mav.addObject("resecond",reChargeDetail.getResecond());
        }else {
            mav.addObject("resecond",0);
        }
        return mav;
    }

    //查询航行轨迹
    @RequestMapping("/drawTrackhis.do")
    @ResponseBody
    public void drawTrackhisByQuery(@RequestParam(value = "shipid")int shipid, @RequestParam(value = "day")String day, HttpServletRequest request, HttpServletResponse response) throws Exception{
//        HttpSession session =request.getSession();
//        int userid = (int) session.getAttribute("userid");
        Map map = new HashMap();
        Date date = new Date();
        if (day !=null&&!StringUtil.isEmpty(day)){
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(5, -Integer.parseInt(day));
            map.put("addt",calendar.getTime());
        }else{
            map.put("addt",date);
        }
        map.put("shipid",shipid);
        map.put("userid",users.getUserid(request));
        List<Map<String,Object>> list = shipInfoDetailService.drawTrackhisByQuery(map);
        List<Map<String,Object>> list1 = new ArrayList<Map<String,Object>>();
        if(list !=null&& list.size()>0) {
            list1.add(list.get(0));
            if ((list1.get(0).get("latitude").equals("0.0")&&list1.get(0).get("longitude").equals("0.0"))||(list1.get(0).get("latitude").equals("-2.0")&&list1.get(0).get("longitude").equals("-2.0"))||(list1.get(0).get("latitude").equals("-1.0")&&list1.get(0).get("longitude").equals("-1.0"))){
                list1.get(0).put("latitude",31.2834987798);
                list1.get(0).put("longitude",118.2421443244);
            }
            for (int i = 0; i < list.size(); i++) {
                if ((list.get(i).get("latitude").equals("0.0")&&list.get(i).get("longitude").equals("0.0"))||(list.get(i).get("latitude").equals("-2.0")&&list.get(i).get("longitude").equals("-2.0"))||(list.get(i).get("latitude").equals("-1.0")&&list.get(i).get("longitude").equals("-1.0"))){
                    continue;
                }
                double ss = FiledUtil.getDistanceFromTwoPoints(Double.parseDouble(list.get(i).get("latitude").toString()), Double.parseDouble(list.get(i).get("longitude").toString()), Double.parseDouble(list1.get(list1.size() - 1).get("latitude").toString()), Double.parseDouble(list1.get(list1.size() - 1).get("longitude").toString()));
                if (ss > 1000) {
                    list1.add(list.get(i));
                }
            }
        }
        PrintWriter printWriter = response.getWriter();
        printWriter.print(StringUtil.toJson(list1));
        printWriter.flush();
        printWriter.close();
    }

    @RequestMapping("/totmslog.do")
    public ModelAndView totmslog()throws Exception{
        ModelAndView mav = new ModelAndView("/common/tmslog");
        return mav;
    }

    @RequestMapping("/toShipManager.do")
    public ModelAndView toShipManager()throws Exception{
        ModelAndView mav = new ModelAndView("/ship/shipManager");
        return mav;
    }

    //查询所有船舶
    @RequestMapping(value = "/selectShipInfosManagerByQuery.do")
    @ResponseBody
    public String selectShipInfosManagerByQuery(@RequestParam(value = "shipname",required=false) String shipname,@RequestParam(value = "isonline",required=false) Integer isonline,@RequestParam(value = "isemtiy",required=false) Integer isemtiy,@RequestParam(value = "page") int page,@RequestParam(value = "limit") int size) throws Exception{
        Map shipMap = new HashMap();
        shipMap.put("shipname",shipname);
        shipMap.put("isonline",isonline);
        shipMap.put("isemtiy",isemtiy);
        List<ShipInfo> shipInfosList = new ArrayList<ShipInfo>();
        int count=0;
        shipInfosList=  shipInfoDetailService.selectShipInfosManagerList(shipMap,page,size);
        count = shipInfoDetailService.selectShipInfosManagerCount(shipMap);
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("code","");
        map.put("msg","");
        map.put("count",count);
        map.put("data",shipInfosList);
        return new ObjectMapper().writeValueAsString(map);
    }

    //修改船主电话
    @RequestMapping("/updateShipownerPhoneByShipid.do")
    @ResponseBody
    public String updateShipownerPhoneByShipid(@RequestParam(value = "shipid") int shipid, @RequestParam(value = "shipownerphone") String shipownerphone) throws Exception{
        shipInfoDetailService.updateShipownerPhoneByShipid(shipid,shipownerphone);
        return  new ObjectMapper().writeValueAsString(true);
    }

    //修改船主姓名
    @RequestMapping("/updateShipownerNameByShipid.do")
    @ResponseBody
    public String updateShipownerNameByShipid(@RequestParam(value = "shipid") int shipid,@RequestParam(value = "shipownername") String shipownername) throws Exception{
        shipInfoDetailService.updateShipownerNameByShipid(shipid,shipownername);
        return  new ObjectMapper().writeValueAsString(true);
    }

    //修改在线状态
    @RequestMapping("/updateIsonlineByShipid.do")
    @ResponseBody
    public String updateIsonlineByShipid(@RequestParam(value = "shipid") int shipid,@RequestParam(value = "isonline") Integer isonline) throws Exception{
        Map map = new HashMap();
        map.put("shipid",shipid);
        if (isonline == 0){
            map.put("isonline",1);
        }else if (isonline==1){
            map.put("isonline",0);
        }
        shipInfoDetailService.updateIsonlineByShipid(map);
        return  new ObjectMapper().writeValueAsString(true);
    }

    //开始观看视频
    @RequestMapping("/startVideo.do")
    @ResponseBody
    public String startVideo(@RequestParam(value = "shipid") int shipid,HttpServletRequest request)throws Exception{
        JiShiDetail jiShiDetail =shipInfoDetailService.selectJiShiDetailBuShipidAndUserid(shipid,users.getUserid(request));
        if (jiShiDetail==null){
            jiShiDetail = new JiShiDetail();
            jiShiDetail.setBegindt(new Timestamp((new Date()).getTime()));
            jiShiDetail.setJsecond(0);
            jiShiDetail.setShipid(shipid);
            jiShiDetail.setUserid(users.getUserid(request));
            shipInfoDetailService.saveJishiDetail(jiShiDetail);
        }else {
            jiShiDetail.setBegindt(new Timestamp((new Date()).getTime()));
            jiShiDetail.setJsecond(0);
            jiShiDetail.setShipid(shipid);
            jiShiDetail.setUserid(users.getUserid(request));
            shipInfoDetailService.updateJishiDetailByquery(jiShiDetail);
        }
        return StringUtil.toJson(true);
    }

    //结束观看视频
    @RequestMapping("/endVideo.do")
    @ResponseBody
    public String endVideo(@RequestParam(value = "shipid") int shipid,HttpServletRequest request)throws Exception{
        Map map =new HashMap();
        Date date = new Date();
        ReChargeDetail reChargeDetail = reChargeService.selectReChargeDetailByUserid(users.getUserid(request));
        JiShiEntiy jiShiEntiy = new JiShiEntiy();
        jiShiEntiy.setUserid(users.getUserid(request));
        jiShiEntiy.setShipid(shipid);
        jiShiEntiy.setEnddate(new Timestamp(date.getTime()));
        JiShiDetail jiShiDetail =shipInfoDetailService.selectJiShiDetailBuShipidAndUserid(shipid,users.getUserid(request));
        if (jiShiDetail !=null){
            jiShiEntiy.setBegindt(jiShiDetail.getBegindt());
            int interval = (int)((date.getTime() - jiShiDetail.getBegindt().getTime())/1000);
            if (reChargeDetail.getResecond()>interval){
//                reChargeDetail.setResecond(reChargeDetail.getResecond()-interval);
                map.put("resecond",reChargeDetail.getResecond()-interval);
                jiShiEntiy.setJsecond(interval);
            }else {
                jiShiEntiy.setJsecond(reChargeDetail.getResecond());
                reChargeDetail.setResecond(0);
            }
        }
        shipInfoDetailService.saveJishientiy(jiShiEntiy);
        map.put("userid",users.getUserid(request));
        reChargeService.updateReChargeDetailByUserid(map);
        return StringUtil.toJson(true);
    }

    //观看统计
    @RequestMapping("/towatchRecord.do")
    public ModelAndView towatchRecord(HttpServletRequest request) throws Exception{
        ModelAndView mav = new ModelAndView("/personal/recharge/watchRecord");
        List<JiShiEntiy> jiShiEntiys = shipInfoDetailService.selectJishientiyByUserid(users.getUserid(request));
        if (jiShiEntiys !=null){
            mav.addObject("jiShiEntiys",jiShiEntiys);
        }
        ReChargeDetail reChargeDetail =reChargeService.selectReChargeDetailByUserid(users.getUserid(request));
        if(reChargeDetail !=null){
            mav.addObject("resecond",reChargeDetail.getResecond());
        }else {
            mav.addObject("resecond",0);
        }
        return  mav;
    }

    //判断设备是否在线
    @RequestMapping("/deviceisonline.do")
    @ResponseBody
    public String deviceIsonlineByQuery(@RequestParam(value = "devicenumber") String devicenumber,@RequestParam(value = "shipid") int shipid) throws Exception{
        String dpwd = "888888";
        int isonline =0;
        int res = Decv.online(devicenumber,dpwd);
        if (res==0){
            isonline=0;
        }else{
            isonline=1;
        }
        Map map = new HashMap();
        if (isonline == 0){
            map.put("isonline",0);
        }else if (isonline==1){
            map.put("isonline",1);
        }
        map.put("shipid",shipid);
        shipInfoDetailService.updateIsonlineByShipid(map);
        return new ObjectMapper().writeValueAsString(res);
    }

    @RequestMapping("/selectDeviceIsthreegeneration.do")
    @ResponseBody
    public String selectDeviceIsthreegeneration(@RequestParam(value = "shipid") int shipid) throws Exception{DeviceInfo deviceInfo = shipInfoDetailService.selectDeviceInfoByShipid(shipid);
        int res = 0;
        String lat = deviceInfo.getLatitude().substring(deviceInfo.getLatitude().indexOf(".")+1);
        String lng = deviceInfo.getLongitude().substring(deviceInfo.getLongitude().indexOf(".")+1);
        if ((deviceInfo.getLongitude().equals("-2.0")&&deviceInfo.getLatitude().equals("-2.0"))||(deviceInfo.getLongitude().equals("-1.0")&&deviceInfo.getLatitude().equals("-1.0"))){
            res =3;
        }else if(deviceInfo.getLongitude().equals("0.0")&&deviceInfo.getLatitude().equals("0.0")){
            res=2;

        }else if(lat.length()<=5&&lat.length()>1&&lng.length()<=5&&lng.length()>1){
            res = 3;
        }else if(lat.length()>5&&lng.length()>5){
            res = 2;
        }
        return new ObjectMapper().writeValueAsString(res);

    }

    @RequestMapping("/selectDeviceVoidurl.do")
    @ResponseBody
    public String selectDeviceVoidurl(@RequestParam(value = "devicenumber") String devicenumber) throws Exception{
        String deviceid=FiledUtil.getDeviceid(devicenumber);
        String msgs= FiledUtil.gethtml5url(deviceid);
        String devicenum = FiledUtil.getdevicechnno(deviceid);
       net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(msgs);
        Map map = new HashMap();
        map.put("ret",Integer.parseInt(jsonObject.getString("ret")));
        if (Integer.parseInt(jsonObject.getString("ret"))==0){
            map.put("devicenum",devicenum);
        }
        return new ObjectMapper().writeValueAsString(map);
    }


}
